package priv.lhy.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import priv.lhy.constans.WebConstant;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Map;

/**
 * author : lihy
 * date : 2019/1/26 10:52
 * <p>
 * JWT token 工具类
 */
public class JwtTokenUtils {

    /**
     * 生成签名key
     *
     * @return
     */
    private static Key generatorKey() {
        //设置加密算法
        SignatureAlgorithm saa = SignatureAlgorithm.HS256;
        //加密签名
        byte[] bin = DatatypeConverter.parseBase64Binary(WebConstant.SIGNATURE_JWT);
        return new SecretKeySpec(bin, saa.getJcaName());
    }

    /**
     * 生成token
     * @param payLoad
     * @return
     */
    public static String generatorToken(Map<String, Object> payLoad) {
        return Jwts.builder()
                .setPayload(JsonUtils.toJson(payLoad))
                .signWith(SignatureAlgorithm.HS256, generatorKey()).compact();
    }

    /**
     * 获取token信息
     * @param token
     * @return
     */
    public static Claims phaseToken(String token) {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(generatorKey()).parseClaimsJws(token);

        return claimsJws.getBody();
    }

    /**
     * 获取token中对应的参数值
     * @param token
     * @param key
     * @return
     */
    public static Object getTokenValue(String token, String key){
        Claims claims = phaseToken(token);
        return claims.get(key);
    }
}
